import Vue from 'vue'
import util from './md5'
import {objKeySort,showToast} from './index'
import md5 from 'js-md5';

var Fly = require("flyio/dist/npm/wx.js")
var fly = new Fly(); //创建fly实例

//配置请求基地址
Vue.prototype.$http = fly
Vue.prototype.$md5 = md5;
// fly.config.baseURL = "http://testme.baojia.com"
// fly.config.baseURL = "http://preme.baojia.com"
// fly.config.baseURL = "https://me.baojia.com"
fly.config.baseURL = "https://api.beidouxintong.com"

//添加拦截器
fly.interceptors.request.use((config, promise) => {

  config.headers={"Content-Type": "application/x-www-form-urlencoded"}

  if (config.url == '/zhanggui-java/auth/xiaochengxu/xiaomi') {
    config.baseURL = 'https://www.beidouxintong.com/app'
    return config;
  }

  var noLoading = config.body ? config.body.noLoading : null
  if (!noLoading) {
    wx.showLoading({
      title: '加载中'
    })
  }

  //接口加密
  var sys = wx.getStorageSync('systemInfo');
  var adCode = wx.getStorageSync('adCode');
  var localtion = wx.getStorageSync('localtion');
  var userInfo = wx.getStorageSync('userInfo');
  var body = config.body || {};
  var timestamp = new Date().getTime();
  var key = md5(timestamp +'')
  var url = config.url
  var str = ''
  var finalData = {}

  var common = {
    // userId: userInfo.userId,
    adCode: adCode || '',
    appFrom: '15', //用户来源(12:蜜蜂出行小程序),
    deviceType: sys.system.indexOf('iOS') != -1 ? '1' : '2',
    // deviceModel: sys.model,
    mobileLatitude: localtion.latitude || 0,
    mobileLongitude: localtion.longitude || 0,
    timestamp: timestamp,
    appVersion: '5.2.0'
  }
  var params = Object.assign(common, body);

  Object.keys(params).forEach(function(key){
    params[key] = params[key] ? params[key]+'' : ''
  });
  if (!userInfo) { //登录前
    let json2 = JSON.stringify(objKeySort(params))
    str = url + '?' + json2 + '?' + key
  } else {
    let token = userInfo.token //登录后
    params.userId = userInfo.userId+''
    let json2 = JSON.stringify(objKeySort(params))
    str = url + '?' + json2 + '?' + token
  }
  // console.log('str:',str);
  common.sign = md5(str)
  finalData = Object.assign(common, params);

  config.body = finalData
  return config;

})

//添加响应拦截器，响应拦截器会在then/catch处理之前执行
fly.interceptors.response.use(
  (response,promise) => {
    //返回结果
    wx.hideLoading()
    const urls = [  //不需要展示错误提示的接口
      '/zhanggui-java/auth/xiaochengxu/renmin',
      '/exc/check/employee/cheackOutCard',
      '/exc/check/login',
      '/bike/refresh/info/v2',
      '/bike/micard/pay',
      '/bike/refund/auditing',
      '/bike/familyCard/add',
    ]
    const codes = [  //不需要展示错误提示的code值
      200,
      412,
      413,
      415
    ]
    let urlStatus = urls.includes(response.request.url)
    let codeStatus = codes.includes(response.data.code)

    if (!urlStatus&&!codeStatus&&response.data.message != '去交押金') {
      if (response.data.message) {
        showToast(response.data.message)
      }
    }

    if(response.data.code == -3){
      wx.setStorageSync('userInfo', null);
      showToast('您的账号已在其他设备登录')
      wx.reLaunch({
        url: '/pages/login/main'
      })
    }
    return response
  },
  (err,promise) => {
    //发生网络错误后会走到这里
    wx.hideLoading()
    showToast('网络信号差，请稍后重试~')
  }
)

export default fly
